package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.Order;
import com.itheima.Product;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 斌叔
 * @description: 模拟高并发下单
 * @create 2022-05-14 22:47
 */
@RestController
@Slf4j
public class OrderController2 {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @RequestMapping("/order/prod/{pid}/{count}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("模拟高并发下单，pid={}", pid);
        //调用查询产品方法
        Product product = productService.findById(pid);
        log.info("查询到{}号商品的信息,内容是:{}", pid, JSON.toJSONString(product));

        //模拟一次网络延迟
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //下单(创建订单)
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //为了不产生太多垃圾数据,暂时不做订单保存
        //orderService.createOrder(order);

        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;
    }


}
